package com.spark.common.helper

import android.arch.lifecycle.Observer

class EventObserver<T>(private val onEventUnHandledContent: (T) -> Unit) : Observer<Event<T>> {
    override fun onChanged(t: Event<T>?) {
        t?.getContentIfNotHandled()?.let {
            onEventUnHandledContent(it)
        }
    }
}


/**
 * Used as wrapper for data that is exposed via a LiveData that respresents an event
 * 明确的管理事件是否已经被处理，从而减少错误
 */

open class Event<out T>(private val content: T) {
    var hasBeenHandled = false
        private set // allow external read but not write

    fun getContentIfNotHandled(): T? {
        return if (hasBeenHandled) {
            null
        } else {
            hasBeenHandled = true
            content
        }
    }

    /**
     * Returns the content,even if it's already been handled.
     */
    fun peekContent(): T = content
}
